import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { ServicesModule } from '../services.module';
import { Observable, EMPTY } from 'rxjs';
import { User } from 'src/app/classes/user';
import { CookieService } from 'ngx-cookie-service';
import { map } from 'rxjs/operators';
import { CLIENT_ID, CLIENT_SECRET, Oauth2 } from 'src/app/classes/oauth2';
import { Router } from '@angular/router';

interface Token {
  access_token: string;
  refresh_token: string;
  expires_in: number;
}

interface CheckToken {
  user_name: string;
  exp: number;
}

@Injectable({
  providedIn: ServicesModule
})
export class UserService {

  constructor(
    private http: HttpClient,
    private cookieService: CookieService,
    private router: Router,
    private oauth2: Oauth2
  ) { }

  /**
   * Check Token
   */
  getUser(): Observable<User> {
    const token = this.cookieService.get('token');
    if (token) {
      // Form Basic Authorization
      const headers = new HttpHeaders().set('Authorization', `Basic ${btoa(CLIENT_ID + ':' + CLIENT_SECRET)}`);
      const params = new HttpParams()
        .set('token', token);
      return this.http.get('/oauth/check_token', { headers, params }).pipe(map((res: CheckToken) => {
        this.cookieService.set('token', token, new Date(Date.now() + res.exp), '/');
        return {
          account: res.user_name,
          exp: res.exp,
        };
      }));
    }
    return EMPTY;
  }

  /**
   * 登录
   * @param username 账号
   * @param password 密码
   */
  login(username: string, password: string): void {
    this.oauth2.putUserNameAndPassword(username, password);

    const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });

    this.http.post('/oauth/token', this.oauth2.getHttpParams(), { headers }).subscribe((r: any) => {
      this.cookieService.set('token', r.access_token, new Date(Date.now() + r.expires_in), '/');
      window.location.href = '';
    });
  }

  /**
   * 退出
   */
  logout(): void {
    const token = this.cookieService.get('token');
    if (token) {
      const params = new HttpParams().set('token', token);
      this.http.delete('/oauth/logout', { params }).subscribe(() => {
        this.cookieService.delete('token');
        window.location.reload();
      });
    }
  }
}
